// 在全局或模块作用域中创建状态存储对象
let checkedState = {};

let checkFile = {};

let currentPath = ""; // 当前路径记录

let rootPath = "";

let machineID = 0;

let machineCode = "";

let machineName = "";

let sessionDownload = null;

let mashineCode = "";

let versionID = "";

let versionName = "";

let confOrExe = "";

let currentFileNamePath = "";

class ListNode {
    constructor(value, isVer, isRoot) {
        this.value = value;
        this.next = null; // 指针初始化为空
        this.prev = null;
        this.isVersioPath = isVer;
        this.isVerRootPath = isRoot;
    }
}


let currentPathID = new ListNode('', false, false);


function closeFileManager() {
    document.getElementById('file-manager-modal').style.display = 'none';
    document.body.style.overflow = 'auto';
}


function LoadDirectory(machineInfo) {
    // 全选功能实现
    let selectAllControl = document.getElementById('selectAll');
    if (selectAllControl) {
        selectAllControl.addEventListener('change', function (e) {
            const checkboxes = document.querySelectorAll('.file-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = e.target.checked;
                // 同步状态存储
                const storageKey = checkbox.dataset.storageKey;
                checkedState[storageKey] = e.target.checked;
            });
        });

        selectAllControl.checked = false;
    }



    machineID = parseInt(machineInfo.id, 10);
    machineCode = machineInfo.machineCode;
    machineName = machineInfo.name;
    currentPath = 'FileList/' + machineCode;
    rootPath = currentPath;
    currentPathID.value = '';
    currentPathID.prev = null;

    renderVersionPath();
}


// 加载目录内容
async function loadDirectory(currentPathID) {
    try {
        // 遍历删除所有键
        Object.keys(checkedState).forEach(key => {
            delete checkedState[key];
        });

        Object.keys(checkFile).forEach(key => {
            delete checkFile[key];
        });

        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        const response = await fetch('/api/file/list', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify({ // 序列化请求体‌:ml-citation{ref="1,3" data="citationList"}
                version_id: versionID, // 需替换为实际版本ID
                machine_id: machineID,
                path: currentPath, // 保持路径编码
                parent_id: currentPathID.value,
            })
        });

        if (!response.ok) {
            //throw new Error(`HTTP 错误! 状态码: ${response.status}`);
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error(`HTTP 错误! 状态码: ${response.status}`);
            }
        } else {
            const data = await response.json();
            if (data == null) {
                toggleBackButton(currentPath);
            } else {
                //renderFileList(data, path);
                renderFileListEx(data);
            }

            //updatePath(currentPath)
        }
    } catch (error) {
        console.error('请求失败:', error);
        throw error; // 继续向上抛出错误
    }
}


function toggleBackButton(path) {
    const buttonConfigs = [
        {
            type: "primary",
            action: "uploadFile()",
            text: "上传文件"
        },

        {
            type: "primary",
            action: "uploadEntrieDir()",
            text: "上传文件目录"
        },
        {
            type: "danger",
            action: "OnDeleteFileList()",
            text: "删除文件"
        },
    ];

    initActionButtons(buttonConfigs);

    const tableManager = new ColumnGroupManager();

    tableManager.remove('ver-name-column');
    tableManager.remove('ver-date-column');
    tableManager.remove('ver-creator-column');
    tableManager.remove('checkbox-column');
    tableManager.remove('filename-column');
    tableManager.remove('action-column-del');
    tableManager.remove('action-column-rename');


    tableManager.add('checkbox-column');
    tableManager.add('filename-column');
    tableManager.add('action-column-del');
    tableManager.add('action-column-rename');




    const headerRow = document.getElementById('version_file_group_head');
    headerRow.innerHTML = `
        <th class="checkbox-column">
            <input type="checkbox" class="bulk-select" id="selectAll">
        </th>
        <th class="filename-column">文件名</th>
        <th class="action-column-del">删除</th>
        <th class="action-column-rename">重命名</th> 
    `;

    let textContentNow = joinAndNormalizePath(machineName + "_" + machineCode, versionName);
    textContentNow = joinAndNormalizePath(textContentNow, confOrExe);
    textContentNow = joinAndNormalizePath(textContentNow, currentFileNamePath);
    document.getElementById('workbenchTitle').textContent = textContentNow;

    const tbody = document.getElementById('file-list-body');
    tbody.innerHTML = ''; // 清空旧内容    


    if (!currentPathID.isVersioPath) {
        const rowBack = document.createElement("tr");
        rowBack.className = "file-row";
        // +++ 新增固定按钮列 +++
        const fixedCell = document.createElement("td");
        const itemback = document.createElement("button");
        itemback.className = 'back-btn'
        itemback.textContent = '...'
        itemback.addEventListener("click", () => {
            goBack();
        });
        fixedCell.appendChild(itemback);
        rowBack.appendChild(fixedCell); // 作为第一列插入
        tbody.appendChild(rowBack);
    }
}


// 渲染文件列表-版本列表
async function renderVersionPath() {
    currentPathID.value = machineCode;
    currentPathID.isVersioPath = true;
    currentPathID.prev = null;
    currentPathID.next = null;

    const buttonConfigs = [
        {
            type: "primary",
            action: "createVersion()",
            text: "创建版本"
        },
        {
            type: "danger",
            action: "deleteVersion()",
            text: "删除版本"
        },
    ];

    initActionButtons(buttonConfigs);

    const tableManager = new ColumnGroupManager();

    tableManager.remove('checkbox-column');
    tableManager.remove('filename-column');
    tableManager.remove('action-column-del');
    tableManager.remove('action-column-rename');
    tableManager.remove('ver-name-column');
    tableManager.remove('ver-date-column');
    tableManager.remove('ver-creator-column');


    tableManager.add('ver-name-column');
    tableManager.add('ver-date-column');
    tableManager.add('ver-creator-column');


    const headerRow = document.getElementById('version_file_group_head');
    headerRow.innerHTML = `
        <th class="ver-name-column">版本</th>
        <th class="ver-date-column">创建时间</th>
        <th class="ver-creator-column">创建人</th>
    `;


    document.getElementById('workbenchTitle').textContent = machineName + "_" + machineCode;


    const cols = document.querySelectorAll('.version_file_table colgroup col');

    // 按类名索引设置宽度（示例）
    cols[0].style.width = '30%';
    //cols[0].style.background = 'yellow';
    cols[0].style.textAlign = 'left';

    cols[1].style.width = '40%';
    cols[1].style.background = 'green';
    cols[1].style.textAlign = 'left';

    cols[2].style.width = '30%';
    //cols[2].style.background = 'blue';
    cols[2].style.textAlign = 'left';


    const tbody = document.getElementById('file-list-body');
    tbody.innerHTML = ''; // 清空旧内容        

    // 设置查询参数
    const params = {
        page: 1,
        pageSize: 20,
        machineID: machineID,
    };

    const response = await GetVersionList(params);
    if (!response.data) {
        return;
    }

    response.data.map(item => {
        const file =
        {
            isDir: true,
            name: item.Name,
            version: item.Version,
            id: item.Id,
            creator: item.Creator,
            createdAt: item.CreatedAt,
        }

        const row = document.createElement("tr");
        row.className = "file-row";

        // 文件名列
        const nameCell = document.createElement("td");
        nameCell.style.textAlign = 'center';
        nameCell.className = "filename-column"; // 必须与colgroup一致
        nameCell.style.width = cols[0].style.width;

        // 图标与名称
        const icon = document.createElement("i");
        icon.className = file.isDir ? "icon-folder" : "icon-file";
        icon.textContent = file.isDir ? "📁 " : "📄 ";

        const nameSpan = document.createElement("span");
        nameSpan.textContent = file.name + "." + file.version;
        nameSpan.className = "filename-text";
        nameSpan.style.cursor = "pointer";
        nameSpan.style.marginLeft = "8px";

        // 保持原有点击逻辑
        if (file.isDir) {
            nameSpan.addEventListener("click", () => {
                currentPathID.next = new ListNode(file.id, false, true)
                currentPathID.next.prev = currentPathID;
                currentPathID = currentPathID.next;

                versionID = file.id
                versionName = file.name + "." + file.version;

                const filePath = joinAndNormalizePath(machineName + "_" + machineCode, versionName);

                currentPath = joinAndNormalizePath(currentPath, file.id);


                renderVerRootPath(filePath);


            });
        }

        nameCell.appendChild(icon);
        nameCell.appendChild(nameSpan);
        row.appendChild(nameCell);


        const dateCell = document.createElement("td");
        //dateCell.style.background = 'yellow';
        dateCell.style.textAlign = 'center';
        dateCell.style.width = cols[1].style.width;
        const dateSpan = document.createElement("span");
        dateSpan.textContent = file.createdAt;
        dateSpan.className = "dateCreate-text";
        dateSpan.style.marginLeft = "8px";
        dateCell.appendChild(dateSpan)
        row.appendChild(dateCell);

        const creatorCell = document.createElement("td");
        //creatorCell.style.background = 'pink';
        creatorCell.style.textAlign = 'center';
        creatorCell.style.width = cols[2].style.width;
        const creatorSpan = document.createElement("span");
        creatorSpan.textContent = file.creator;
        creatorSpan.className = "Creator-text";
        creatorSpan.style.textAlign = 'center';
        creatorCell.appendChild(creatorSpan);
        row.appendChild(creatorCell);

        tbody.appendChild(row);
    });
}

// 渲染文件列表
function renderVerRootPath(filepath) {

    const buttonConfigs = [
    ];

    initActionButtons(buttonConfigs);


    const tableManager = new ColumnGroupManager();


    tableManager.remove('ver-name-column');
    tableManager.remove('ver-date-column');
    tableManager.remove('ver-creator-column');
    tableManager.remove('checkbox-column');
    tableManager.remove('filename-column');
    tableManager.remove('action-column-del');
    tableManager.remove('action-column-rename');


    tableManager.add('checkbox-column');
    tableManager.add('filename-column');
    tableManager.add('action-column-del');
    tableManager.add('action-column-rename');




    const headerRow = document.getElementById('version_file_group_head');
    headerRow.innerHTML = `
        <th class="checkbox-column">
            <input type="checkbox" class="bulk-select" id="selectAll">
        </th>
        <th class="filename-column">文件名</th>
        <th class="action-column-del">删除</th>
        <th class="action-column-rename">重命名</th> 
    `;


    document.getElementById('workbenchTitle').textContent = filepath;


    const cols = document.querySelectorAll('.version_file_table colgroup col');
    cols[0].style.width = '10%';
    cols[1].style.width = '30%';
    cols[2].style.width = '30%';
    cols[3].style.width = '30%';

    const tbody = document.getElementById('file-list-body');
    tbody.innerHTML = ''; // 清空旧内容    


    const rowBack = document.createElement("tr");
    rowBack.className = "file-row";
    // +++ 新增固定按钮列 +++
    const fixedCell = document.createElement("td");
    const itemback = document.createElement("button");
    itemback.className = 'back-btn'
    itemback.textContent = '...'
    itemback.addEventListener("click", () => {
        goBack();
    });
    fixedCell.appendChild(itemback);
    rowBack.appendChild(fixedCell); // 作为第一列插入
    tbody.appendChild(rowBack);

    const files = [
        {
            isDir: true,
            name: '执行程序',
            id: 'process',
        },
        {
            isDir: true,
            name: '配置文件',
            id: 'conf',
        }
    ]
    files.forEach(file => {
        const row = document.createElement("tr");
        row.className = "file-row";

        //复选框列
        const checkboxCell = document.createElement("td");
        //checkboxCell.style.background = 'green';
        checkboxCell.style.width = cols[0].style.width;
        checkboxCell.className = "checkbox-column"; // 应用预定义的CSS类
        row.appendChild(checkboxCell);

        // 文件名列
        const nameCell = document.createElement("td");
        nameCell.className = "filename-column"; // 必须与colgroup一致
        //nameCell.style.background = 'yellow';
        nameCell.style.textAlign = 'center';
        nameCell.style.width = cols[1].style.width;

        // 图标与名称
        const icon = document.createElement("i");
        icon.className = file.isDir ? "icon-folder" : "icon-file";
        icon.textContent = file.isDir ? "📁 " : "📄 ";

        const nameSpan = document.createElement("span");
        nameSpan.textContent = file.name;
        nameSpan.className = "filename-text";
        nameSpan.style.marginLeft = "8px";
        nameSpan.style.cursor = "pointer";

        // 保持原有点击逻辑
        if (file.isDir) {
            nameSpan.addEventListener("click", () => {
                currentPathID.next = new ListNode(file.id, false, false)
                currentPathID.next.prev = currentPathID;
                currentPathID = currentPathID.next;

                currentPath = joinAndNormalizePath(currentPath, file.id);

                confOrExe = file.name

                currentFileNamePath = '';

                loadDirectory(currentPathID)
            });
        } else {
            //nameSpan.addEventListener("click", () => handleFileClick(file));
        }

        nameCell.appendChild(icon);
        nameCell.appendChild(nameSpan);
        row.appendChild(nameCell);


        // 创建删除按钮
        const deleteBtn = createButton(
            'fas fa-trash',
            'trash-btn',
            async () => { // 关键点1：将回调改为 async 函数
                //console.error('该目录为固定目录，不支持删除');
                const result = await ShowErrorModal('该目录为固定目录，不支持删除', {
                    title: '操作失败',
                    buttons: [
                        {
                            text: '确定',
                            type: 'confirm',
                            onClick: () => console.log('确认')
                        }
                    ]
                });
            }
        );

        // 创建重命名按钮
        const renameBtn = createButton(
            'fas fa-pen',  // 铅笔图标           
            'rename-btn',
            async () => {
                const result = await ShowErrorModal('该目录为固定目录，不支持重命名', {
                    title: '操作失败',
                    buttons: [
                        {
                            text: '确定',
                            type: 'confirm',
                            onClick: () => console.log('确认')
                        }
                    ]
                });
            }
        );


        const tdDel = document.createElement("td");
        //tdDel.style.background = 'red';
        tdDel.style.textAlign = 'center';
        tdDel.style.width = cols[2].style.width;
        tdDel.className = "action-column-del"
        tdDel.appendChild(deleteBtn);

        const tdRename = document.createElement("td");
        tdRename.style.textAlign = 'center';
        //tdRename.style.background = 'pink';
        tdRename.style.width = cols[3].style.width;
        tdRename.className = "action-column-rename"
        tdRename.appendChild(renameBtn);


        // 添加操作列
        row.appendChild(tdDel);
        row.appendChild(tdRename);

        tbody.appendChild(row);
    });
}


// 渲染文件列表
function renderFileListEx(files) {
    const buttonConfigs = [
        {
            type: "primary",
            action: "uploadFile()",
            text: "上传文件"
        },

        {
            type: "primary",
            action: "uploadEntrieDir()",
            text: "上传文件目录"
        },
        {
            type: "danger",
            action: "OnDeleteFileList()",
            text: "删除文件"
        },
    ];

    initActionButtons(buttonConfigs);


    const tableManager = new ColumnGroupManager();

    tableManager.remove('ver-name-column');
    tableManager.remove('ver-date-column');
    tableManager.remove('ver-creator-column');
    tableManager.remove('checkbox-column');
    tableManager.remove('filename-column');
    tableManager.remove('filesize-column');
    tableManager.remove('action-column-del');
    tableManager.remove('action-column-rename');


    tableManager.add('checkbox-column');
    tableManager.add('filename-column');
    tableManager.add('filesize-column');
    tableManager.add('action-column-del');
    tableManager.add('action-column-rename');


    const headerRow = document.getElementById('version_file_group_head');
    headerRow.innerHTML = `
        <th class="checkbox-column">
            <input type="checkbox" class="bulk-select" id="selectAll">
        </th>
        <th class="filename-column">文件名</th>
        <th class="filesize-column">文件大小</th>
        <th class="action-column-del">删除</th>
        <th class="action-column-rename">重命名</th> 
    `;


    // 全选功能实现
    let selectAllControl = document.getElementById('selectAll');
    if (selectAllControl) {
        selectAllControl.addEventListener('change', function (e) {
            const checkboxes = document.querySelectorAll('.file-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = e.target.checked;
                // 同步状态存储
                const storageKey = checkbox.dataset.storageKey;
                checkedState[storageKey] = e.target.checked;
            });
        });

        selectAllControl.checked = false;
    }



    const cols = document.querySelectorAll('.version_file_table colgroup col');
    cols[0].style.width = '10%';
    cols[1].style.width = '55%';
    cols[2].style.width = '15%';
    cols[3].style.width = '10%';
    cols[4].style.width = '10%';

    let textContentNow = joinAndNormalizePath(machineName + "_" + machineCode, versionName);
    textContentNow = joinAndNormalizePath(textContentNow, confOrExe);
    textContentNow = joinAndNormalizePath(textContentNow, currentFileNamePath);
    document.getElementById('workbenchTitle').textContent = textContentNow

    const tbody = document.getElementById('file-list-body');
    tbody.innerHTML = ''; // 清空旧内容    


    if (!currentPathID.isVersioPath) {
        const rowBack = document.createElement("tr");
        rowBack.className = "file-row";
        // +++ 新增固定按钮列 +++
        const fixedCell = document.createElement("td");
        const itemback = document.createElement("button");
        itemback.className = 'back-btn'
        itemback.textContent = '...'
        itemback.addEventListener("click", () => {
            goBack();
        });
        fixedCell.appendChild(itemback);
        rowBack.appendChild(fixedCell); // 作为第一列插入
        tbody.appendChild(rowBack);
    }

    files.forEach(file => {
        const row = document.createElement("tr");
        row.className = "file-row";

        // 复选框列
        const checkboxCell = document.createElement("td");
        checkboxCell.style.width = cols[0].style.width;
        checkboxCell.style.textAlign = 'center';
        //checkboxCell.style.background = 'yellow';

        // 复选框生成逻辑（保持原有代码）
        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.className = "file-checkbox";
        const storageKey = file.path.replace(/\//g, '_') + file.name;
        checkbox.dataset.storageKey = storageKey;
        checkbox.checked = false;
        checkFile[storageKey] = file;
        checkbox.addEventListener('change', (e) => {
            checkedState[storageKey] = e.target.checked;
            console.info("file:", checkFile[storageKey].name)
        });

        checkboxCell.appendChild(checkbox);
        checkboxCell.className = "checkbox-column"; // 应用预定义的CSS类
        row.appendChild(checkboxCell);

        // 文件名列
        const nameCell = document.createElement("td");
        nameCell.className = "filename-column"; // 必须与colgroup一致
        nameCell.style.width = cols[1].style.width;
        nameCell.style.textAlign = 'center';

        // 图标与名称
        const icon = document.createElement("i");
        icon.className = file.isDir ? "icon-folder" : "icon-file";
        const iconContent = renderFileIcon(file.name, file.isDir)
        icon.textContent = iconContent;
        //const iconName = vscodeIcons.getIconForFile(file.name);
        //icon.body.innerHTML = renderFileIcon(file.name);

        const nameSpan = document.createElement("span");
        nameSpan.textContent = file.name;
        nameSpan.className = "filename-text";
        nameSpan.style.marginLeft = "8px";
        nameSpan.style.cursor = "pointer";

        // 保持原有点击逻辑
        if (file.isDir) {
            nameSpan.addEventListener("click", () => {
                currentPathID.next = new ListNode(file.id, false, false)
                currentPathID.next.prev = currentPathID;
                currentPathID = currentPathID.next;

                currentFileNamePath = joinAndNormalizePath(currentFileNamePath, file.name);
                currentPath = joinAndNormalizePath(currentPath, file.id);

                loadDirectory(currentPathID);
            });
        } else {
            //nameSpan.addEventListener("click", () => handleFileClick(file));
        }

        nameCell.appendChild(icon);
        nameCell.appendChild(nameSpan);
        row.appendChild(nameCell);


        const fileSizeCell = document.createElement("td");
        fileSizeCell.style.width = cols[2].style.width;
        fileSizeCell.style.textAlign = 'center';
        const fileSizeSpan = document.createElement("span");
        fileSizeSpan.textContent = formatFileSize(file.size);
        fileSizeSpan.className = "filename-text";
        fileSizeSpan.style.marginLeft = "8px";
        fileSizeSpan.style.cursor = "pointer";
        fileSizeCell.appendChild(fileSizeSpan);
        row.appendChild(fileSizeCell);

        // 创建删除按钮
        const deleteBtn = createButton(
            'fas fa-trash',
            'trash-btn',
            async () => { // 关键点1：将回调改为 async 函数
                try {
                    await deleteSelf(file); // 关键点2：等待异步操作完成
                    await loadDirectory(currentPathID);
                } catch (error) {
                    console.error('删除失败:', error);
                    // 可添加错误提示逻辑，例如：
                    // showErrorToast('文件删除失败');
                }
            }
        );

        // 创建重命名按钮
        const renameBtn = createButton(
            'fas fa-pen',  // 铅笔图标           
            'rename-btn',
            async () => {
                const newName = prompt('请输入新名称：');
                if (newName) {
                    const renameResult = await renameFile(file.path + file.name, newName, file.id);
                    if (renameResult.success) {
                        loadDirectory(currentPathID);
                    } else {
                        alert(`操作失败: ${renameResult.error}`);
                    }
                }
            }
        );


        const tdDel = document.createElement("td");
        tdDel.style.width = cols[3].style.width;
        tdDel.style.textAlign = 'center';
        tdDel.className = "action-column-del"
        tdDel.appendChild(deleteBtn);

        const tdRename = document.createElement("td");
        tdRename.style.width = cols[4].style.width;
        tdRename.style.textAlign = 'center';
        tdRename.className = "action-column-rename"
        tdRename.appendChild(renameBtn);


        // 添加操作列
        row.appendChild(tdDel);
        row.appendChild(tdRename);

        tbody.appendChild(row);
    });
}

function goBack() {
    if (currentPathID.prev == null) {
        currentPath = joinAndNormalizePath('FileList/', machineCode)
        renderVersionPath();
    } else {
        currentPathID = currentPathID.prev;

        if (currentPathID.isVersioPath) {
            currentPath = joinAndNormalizePath('FileList/', machineCode)
            renderVersionPath();
        } else if (currentPathID.isVerRootPath) {
            currentPath = joinAndNormalizePath('FileList/', machineCode)

            let filePath = joinAndNormalizePath(machineName + "_" + machineCode, versionName)

            currentPath = joinAndNormalizePath(currentPath, versionID)

            renderVerRootPath(filePath);
        } else {
            currentPath = getParentDirectory(currentPath);
            currentFileNamePath = getParentDirectory(currentFileNamePath);
            loadDirectory(currentPathID);
        }
    }
}


function updatePath(newPath) {

    const result = removePathPrefix(newPath, "FileList");

    //document.getElementById('current-path').value = "\\" + result;
}


function removePathPrefix(path, prefix) {
    const formatPath = p => p.replace(/\\/g, '/').toLowerCase();
    const normalizedPath = formatPath(path);
    const normalizedPrefix = formatPath(prefix);

    return normalizedPath.startsWith(normalizedPrefix)
        ? path.slice(prefix.length).replace(/^[/\\]/, '')
        : path;
}


function uploadFile() {
    const input = document.createElement('input');
    input.type = 'file';
    input.hidden = true;
    input.multiple = true;
    input.webkitdirectory = false;
    input.addEventListener('change', async e => {
        const files = e.target.files;
        if (!files.length) return;


        try {
            chunkedUploadEx(files);
        } catch (error) {
            console.error('上传流程中断:', error);
            alert(`上传失败: ${error.message}`);
        }
    });

    document.body.appendChild(input);
    input.click();
    input.remove();

    // 显示上传弹窗
    //document.getElementById('upload-modal').style.display = 'block';
}

// 修改后的上传入口函数
async function chunkedUploadEx(files) {
    try {
        if (!files.length) return;

        // 构造请求体
        const requestBody = {
            fileList: [],
            reqcode: 'testreq',
            version: versionID
        };

        Array.from(files).forEach(file => {
            let strFileFullPath = joinAndNormalizePath(currentPath, file.name)
            if (file.webkitRelativePath.length > 0) {
                strFileFullPath = joinAndNormalizePath(currentPath, file.webkitRelativePath)
            }
            strFileFullPath = removePrefix(strFileFullPath)
            requestBody.fileList.push({
                name: strFileFullPath
            })
        });


        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        // 发起请求
        const response = await fetch('/api/version/add_subversion', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify(requestBody),
        });

        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                alert(`删除失败,接口调用失败`)
            }
        } else {
            // 解析业务数据
            const result = await response.json();
            // 根据code字段判断业务状态
            if (result.code === "0") {

            } else {
                alert("业务错误:", result.message);
                throw new Error(result.message || "未知业务错误");
            }

        }


        // 显示上传弹窗
        document.getElementById('upload-modal').style.display = 'block';

        const sessionMgr = new SessionManager();

        sessionControl = sessionMgr;

        sessionMgr.startUpdateUI();
        // 添加所有文件到上传队列
        Array.from(files).forEach(file => {
            sessionMgr.addUpload(file)
        });
    } catch (error) {
        // 统一错误处理
        console.error('请求失败:', error.message);

        // 特殊处理网络错误
        if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
            console.error('网络连接异常，请检查网络设置');
        }

        // 抛出错误供上层处理
        throw error;
    }
}

function uploadEntrieDir() {       
    if (!('webkitdirectory' in document.createElement('input'))) {
        document.getElementById('status').textContent = '当前浏览器不支持文件夹选择';
        return;
    }

    const input = document.createElement('input');
    input.type = 'file';
    input.webkitdirectory = true;
    input.multiple = true;

    input.addEventListener('change', (event) => {
        const files = event.target.files;
        const statusEl = document.getElementById('status');

        if (files.length === 0) {
            statusEl.textContent = '未选择文件夹';
            return;
        }

        try {
             // 显示上传弹窗
            document.getElementById('upload-modal').style.display = 'block';

            chunkedUploadEx(files);
        } catch (error) {
            console.error('上传流程中断:', error);
            alert(`上传失败: ${error.message}`);
        }


        loadDirectory(currentPathID);
    });

    input.click();

}


async function OnDownloadByList() {
    // 显示上传弹窗
    document.getElementById('upload-modal').style.display = 'block';

    // 创建Promise数组（并行执行）
    const sessionMgr = new SessionManager();
    sessionDownload = sessionMgr;
    Object.keys(checkedState)
        .filter(key => checkedState[key] && checkFile.hasOwnProperty(key))
        .map(async key => {
            if (checkFile[key].name != "") {
                sessionMgr.addDownload(checkFile[key]);
            }
        });
}

async function OnDeleteFileList() {
    try {
        // 创建Promise数组（并行执行）
        const deletePromises = Object.keys(checkedState)
            .filter(key => checkedState[key] && checkFile.hasOwnProperty(key))
            .map(async key => {
                const response = await deleteSelf(checkFile[key]);
                return response.json(); // 自动包装为Promise
            });

        // 等待所有删除操作完成
        const results = await Promise.allSettled(deletePromises);

        // 处理操作结果
        results.forEach((result, index) => {
            if (result.status === "fulfilled") {
                console.info(`文件 ${Object.keys(checkedState)[index]} 删除成功:`, result.value);
            } else {
                console.error(`文件 ${Object.keys(checkedState)[index]} 删除失败:`, result.reason);
            }
        });
    } catch (error) {
        console.error("批量删除操作异常:", error);
    } finally {
        // 无论成功失败都刷新目录
        await loadDirectory(currentPathID);
        document.getElementById('selectAll').checked = false;
    }
}



// 上传管理器
class SessionManager {
    Uploads;
    Downloads;
    _cancelHandlerBound;
    startIndex;
    EndIndex;

    constructor() {
        this.Uploads = new Map();
        this.Downloads = new Map();
        this._cancelHandlerBound = false; // 事件委托标记
        this.startIndex = 0;
        this.EndIndex = 10;

        this.updateTimer = null;
        //this.startUpdateUI();
    }

    addUpload(file, chunkSize = 5 * 1024 * 1024) {
        const uploadId = generateUUID();

        //this.Uploads = new Map();

        this.Uploads.set(uploadId, {
            file,
            progress: 0,
            chunksDone: 0,
            totalChunks: file.size == 0? 1: Math.ceil(file.size / chunkSize),
            controller: new AbortController(),
            status: 'pending'
        });
                
        this.startUpload(uploadId, chunkSize);
    }


    addDownload(file) {
        const DownloadId = generateUUID();

        //this.Downloads = new Map();

        this.Downloads.set(DownloadId, {
            file,
            progress: 0,
            chunksDone: 0,
            status: 'pending'
        });

        this.updateDownloadUI();

        const data = this.Downloads.get(DownloadId);
        if (!data) {
            console.error("upload data missing:", DownloadId);
            isProcessing = false;
            return;
        }

        this.downloadWithProgress(DownloadId, data.file.path, data.file.name);
    }


    async startUpload(uploadId, chunkSize) {

        const data = this.Uploads.get(uploadId);

        if (!data) {
            console.error("upload data missing:", uploadId);
            isProcessing = false;
            return;
        }

        try {

            data.status = 'uploading';

            const { file, totalChunks, controller } = data;

            for (let index = 0; index < totalChunks; index++) {
                // 每次循环前重新获取最新状态
                const currentData = this.Uploads.get(uploadId);
                if (!currentData || controller.signal.aborted) break;

                // 上传分片逻辑...
                await uploadChunk(data.file, index, uploadId, data.totalChunks, chunkSize);

                let filePathIndex = joinAndNormalizePath(currentPath, data.file.webkitRelativePath);
                if (data.file.webkitRelativePath.length == 0) {
                    filePathIndex = joinAndNormalizePath(currentPath, data.file.name);
                }


                if (index === totalChunks - 1) {
                    const mergePayload = {
                        uploadId,
                        filename: data.file.name,
                        filePath: filePathIndex,
                        currentPath: currentPath,
                        version: versionID,
                        machine: machineID,
                        parent_id: currentPathID.value,
                    };

                    // 获取认证信息（根据实际存储方式调整）
                    const token = localStorage.getItem('authToken');
                    if (!token) AuthReDirection(false);

                    const response = await fetch('/api/upload/merge', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `${token}`,
                        },
                        body: JSON.stringify(mergePayload)
                    });


                    if (response.status == 401) {
                        AuthReDirection(false);
                    }
                    else if (response.status == 402) {
                        const data = await response.json();
                        AuthPermissionErr(data.error);
                        return
                    }
                    else {                        
                         // 重命名响应数据变量
                        const responseData = await response.json();
                        if (responseData.code === "0") {
                            console.log('合并成功');                           
                            this.Uploads.set(uploadId, {
                                ...currentData,
                                progress: 100,
                                chunksDone: index + 1,
                                status: 'completed'
                            });
                        } else {
                            console.error('合并失败:', responseData.message);
                            
                            this.Uploads.set(uploadId, {
                                ...currentData,
                                status: 'error',
                                error: responseData.message
                            });
                        }
                    }
                   
                }
                else {
                    // 使用原子更新
                    this.Uploads.set(uploadId, {
                        ...currentData,
                        chunksDone: index + 1,
                        progress: ((index + 1) / totalChunks) * 100
                    });

                    //this.updateUI();
                }
            }

            // 最终状态检查
            const finalData = this.Uploads.get(uploadId);
            if (finalData) {
                if (controller.signal.aborted) {
                    this.Uploads.set(uploadId, {
                        ...data,
                        status: 'canceled'
                    });
                }
            }
        } catch (error) {
            // 提取错误堆栈中的行号
            const stackLines = error.stack?.split('\n') || [];
            let errorLine = "Unknown";

            // 遍历堆栈的每一行（字符串）
            for (const line of stackLines) {
                // 修正正则表达式，匹配 (文件路径:行号:列号)
                const match = line.match(/[（(](.+?):(\d+):(\d+)[）)]/);
                if (match) {
                    const [_, filePath, lineNum, column] = match;
                    errorLine = `文件: ${filePath}, 行: ${lineNum}`;
                    break;
                }
            }
            // 更新状态为部分失败
            this.Uploads.set(uploadId, {
                ...data,
                status: 'error',
                error: error.message + " in:" + errorLine
            });
            //console.log(error.message)
        } finally {
            //this.updateUI();

            //loadDirectory(currentPath);
        }
    }

    // 关闭弹窗
    closeUploadModal() {
        const modal = document.getElementById('upload-modal');
        modal.style.display = 'none';
    }

    cancelUpload(uploadId) {
        const data = this.Uploads.get(uploadId);
        if (data) {
            data.controller.abort();
            data.status = 'canceled';            
        }
    }

    cancelAll() {
        for (const [uploadId, data] of this.Uploads.entries()) {
            data.controller.abort();
            data.status = 'canceled';
        }

        this.closeUploadModal();
    }

    startUpdateUI(){
        this.updateTimer = setInterval(() => this.timeUpdateUI(), 100);
    }
       
    stopUpdateUI() {
        if (this.updateTimer) {
          clearInterval(this.updateTimer);
          this.updateTimer = null;
        }
    }

    renderVisibleItems(start, end) {
        const container = document.getElementById('error-list');        
        const pool = Array.from(container.children);
        container.innerHTML = '';
        
        const buttonTextMap = {
            canceled: '已取消',
            error: '重新上传',
            completed: '已完成',
            uploading: '取消上传',
            paused: '继续上传',
            pending: '开始上传'
        };

        const buttonClass = {
            canceled: 'cancel-btn',
            error: 'cancel-btn',
            completed: 'complate-btn',
            uploading: 'cancel-btn',
            paused: 'cancel-btn',
            pending: 'cancel-btn'
        }

        Array.from(this.Uploads.entries())
            .slice(start, end).forEach(([uploadId, data], index)  => {
            //let item = pool[index] ||  document.createElement('div');            
            // item.className = 'upload-item';
            // item.innerHTML = `
            // <div class="file-info">
            //     <div>${data.file.name}</div>
            //     <div>${(data.file.size / 1024 / 1024).toFixed(2)} MB</div>
            // </div>
            // <div class="progress-container">
            //     <div class="progress-bar" style="width: ${data.progress}%"></div>
            //     <div class="progress-info">
            //     <span>${data.chunksDone}/${data.totalChunks} chunks</span>
            //     <span>${data.progress.toFixed(1)}%</span>
            //     </div>
            // </div>
            // <button class="${buttonClass[data.status]}" 
            //         data-id="${uploadId}"
            //             ${['completed', 'canceled'].includes(data.status) ? 'disabled' : ''}>
            //     ${buttonTextMap[data.status] || '未知状态'}
            // </button>
            
            // ${data.status === 'error' ?
            //             `<div class="error-message">${data.error}</div>` : ''}
            // `;

            // if (!item.parentNode) {
            //     container.appendChild(item);
            // }
                 
        });                
    }

    timeUpdateUI(){        
        this.updateUI();
    }
   
    updateUI() {
        let activeCount = 0;  
   
        let bAllFinish = true;

        let nCompleted = 0;

        let arrayErrorData = [];
        for (const [uploadId, data] of this.Uploads.entries()) {        
            if (['uploading', 'pending'].includes(data.status)) activeCount++;

            if (data.status != "completed" && data.status != "error") {
                bAllFinish = false;
            }else {
                nCompleted++;

                if(data.status == "error"){
                    arrayErrorData.push(data);
                }
            }
        }

        const uploadCount = document.getElementById('active-uploads');
        uploadCount.textContent = String(nCompleted) + '/' + String(this.Uploads.size);
        
        let nProcess = nCompleted.toFixed(2) / this.Uploads.size.toFixed(2);
        nProcess = nProcess.toFixed(2) * 100;


        //upload-process
        const uploadProcess = document.getElementById('upload-process');
        uploadProcess.innerHTML = '';
        const item = document.createElement('div');
        item.className = 'upload-item';
        item.innerHTML = `
        <div class="progress-container">
            <div class="progress-bar" style="width: ${nProcess}%"></div>
            <div class="progress-info">
            <span>${nCompleted}/${this.Uploads.size}</span>            
            </div>
        </div>
        `
        uploadProcess.appendChild(item);


        const cancelBtn = document.getElementById('cancel-all-button');
        if (bAllFinish) {
            cancelBtn.textContent = '上传完成，点击退出';
            cancelBtn.onclick = OnAllCompQuit;
            cancelBtn.style.backgroundColor = '#44ff6d';

            const container = document.getElementById('error-list');
            container.innerHTML = '';

            for(let i = 0; i < arrayErrorData.length; i++){
                const data = arrayErrorData[i];
                const errItem = document.createElement('div');
                errItem.innerHTML = `
                    <div class="file-info">
                        <div>${data.file.name}</div>
                        <div>${(data.file.size / 1024 / 1024).toFixed(2)} MB</div>
                        <div class="error-message">${data.error}</div>
                    </div>
                `
                container.appendChild(errItem);
            }
            
            this.stopUpdateUI();

            const uploadFileName = document.getElementById('uploadfilename');
            uploadFileName.textContent = "";
        } else {
            cancelBtn.textContent = '⛔ 停止全部上传';
            cancelBtn.onclick = OnCancelAll;
            cancelBtn.style.backgroundColor = '#ff4444';
        }
    }


    updateDownloadUI() {
        const container = document.getElementById('error-list');
        container.innerHTML = '';

        let activeCount = 0;

        const buttonTextMap = {
            canceled: '已取消',
            error: '重新下载',
            completed: '已完成',
            Downloading: '取消下载',
            paused: '继续下载',
            pending: '开始下载'
        };

        const buttonClass = {
            canceled: 'cancel-btn',
            error: 'cancel-btn',
            completed: 'complate-btn',
            Downloading: 'cancel-btn',
            paused: 'cancel-btn',
            pending: 'cancel-btn'
        }

        let bAllFinish = true;

        for (const [donwloadId, data] of this.Downloads.entries()) {
            console.log(`ID: ${donwloadId}`, `状态: ${data.status}`);

            const item = document.createElement('div');
            item.className = 'upload-item';
            item.innerHTML = `
          <div class="file-info">
            <div>${data.file.name}</div>
            <div>${(data.file.size / 1024 / 1024).toFixed(2)} MB</div>
          </div>
          <div class="progress-container">
            <div class="progress-bar" style="width: ${data.progress}%"></div>
            <div class="progress-info">
              <span>${data.chunksDone}/${data.totalChunks} chunks</span>
              <span>${data.progress}%</span>
            </div>
          </div>
          <button class="${buttonClass[data.status]}" 
                data-id="${donwloadId}"
                    ${['completed', 'canceled'].includes(data.status) ? 'disabled' : ''}>
            ${buttonTextMap[data.status] || '未知状态'}
          </button>
          
          ${data.status === 'error' ?
                    `<div class="error-message">${data.error}</div>` : ''}
        `;
            container.appendChild(item);

            if (['uploading', 'pending'].includes(data.status)) activeCount++;

            if (data.status != "completed") {
                bAllFinish = false;
            }
        }

        const cancelBtn = document.getElementById('cancel-all-button');
        if (bAllFinish) {
            cancelBtn.textContent = '下载完成，点击退出';
            cancelBtn.onclick = OnAllCompQuit;
            cancelBtn.style.backgroundColor = '#44ff6d';
        } else {
            cancelBtn.textContent = '⛔ 停止全部下载';
            cancelBtn.onclick = OnCancelAll;
            cancelBtn.style.backgroundColor = '#ff4444';
        }
    }

    async getFileSize(filePath, fileName) {
        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);
        const response = await fetch('/api/download', { // 替换为实际接口地址
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify({
                path: filePath,
                name: fileName,
                method: "getSize" // 触发获取文件大小
            })
        });

        if (!response.ok) {
            if (responseData.code === "0") {
                console.log('合并成功');
                //data.status = 'completed';
                // 原子化更新
                this.Uploads.set(uploadId, {
                    ...currentData,
                    progress: 100,
                    chunksDone: index + 1,
                    status: 'completed'
                });
            } else {
                if (response.status == 401) {
                    AuthReDirection(false);
                }
                else if (response.status == 402) {
                    const data = await response.json();
                    AuthPermissionErr(data.error);
                    return
                }
                else {
                    throw new Error('获取文件大小失败');
                }
            }

        }
        const data = await response.json();
        return parseInt(data.fileSize); // 返回字节数
    }


    async downloadWithProgress(DownloadID, filePath, fileName) {

        const data = this.Downloads.get(DownloadID);
        if (!data) {
            return;
        }

        data.status = "Downloading";
        this.Downloads.set(DownloadID, data); // 立即更新状态

        // 1. 获取文件大小
        const fileSize = await this.getFileSize(filePath, fileName);

        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);
        // 2. 初始化下载
        const response = await fetch('/api/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Range': `bytes=0-`,
                'Authorization': `${token}`,
            },
            body: JSON.stringify({ path: filePath, name: fileName })
        });

        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error('下载文件失败');
            }
        }
        // 3. 创建可读流
        const reader = response.body.getReader();
        let received = 0;

        // 4. 实时处理数据
        const chunks = [];
        while (true) {
            // 每次循环前重新获取最新状态
            const currentData = this.Downloads.get(DownloadID);

            // 主动终止条件
            if (!currentData || currentData.status === "Cancelled") {
                console.log("Download cancelled or removed");
                reader.cancel();  // 重要！释放资源
                controller.abort();
                break;
            }


            const { done, value } = await reader.read();
            if (done) break;

            chunks.push(value);
            received += value.length;

            // 更新进度条（示例）
            const progress = (received / fileSize * 100).toFixed(2);
            console.log(`下载进度: ${progress}%`);


            // 使用原子更新
            this.Downloads.set(DownloadID, {
                ...currentData,
                progress: progress
            });

            this.updateDownloadUI();
        }

        // 5. 合并数据并下载
        const fullData = new Uint8Array(received);
        let offset = 0;
        for (const chunk of chunks) {
            fullData.set(chunk, offset);
            offset += chunk.length;
        }

        // 合并数据（建议替换为流式写入）
        const blob = new Blob(chunks);
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setTimeout(() => URL.revokeObjectURL(url), 1000);

        this.Downloads.set(DownloadID, {
            ...data,
            status: "completed",
            progress: 100
        });
        this.updateDownloadUI();
    }

};


// 生成UUID函数
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0;
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

function OnCancelAll() {
    if (sessionControl) {
        sessionControl.cancelAll();
    }

    if (sessionDownload) {
        sessionDownload.closeUploadModal();
    }

    loadDirectory(currentPathID);
}

function OnAllCompQuit() {
    if (sessionControl) {
        sessionControl.closeUploadModal();
    }

    if (sessionDownload) {
        sessionDownload.closeUploadModal();
    }

    loadDirectory(currentPathID);
}


async function uploadChunk(file, index, uploadId, totalChunks, chunkSize) {
    const start = index * chunkSize;
    const end = Math.min(file.size, start + chunkSize);
    const chunk = file.slice(start, end);

    const formData = new FormData();
    formData.append('file', chunk);
    formData.append('uploadId', uploadId);
    formData.append('chunkIndex', index);
    formData.append('totalChunks', totalChunks);
    formData.append('filename', file.name);
    formData.append('size', end - start);

    try {

        const container = document.getElementById('uploadfilename');
        container.textContent = `正在上传文件切片 ${index + 1}/${totalChunks},文件:${file.name}`;

        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);
        const response = await fetch('/api/upload/chunk', {
            method: 'POST',
            body: formData,
            headers: {
                'Authorization': `${token}`,
            },
        });

        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error(`HTTP ${response.status}`);
            }
        }


        console.log(`分片 ${index + 1}/${totalChunks} 上传成功`);
    } catch (error) {
        console.error(`分片 ${index} 上传失败:`, error);
        return false;
    }

    return true;
}

function joinAndNormalizePath(basePath, subPath) {
    if (basePath == null || basePath.length == 0) {
        return subPath;
    }

    if (subPath == null || subPath.length == 0) {
        return basePath;
    }

    // 统一路径分隔符为斜杠
    const unifiedBase = basePath.replace(/\\/g, '/');
    const unifiedSub = subPath.replace(/\\/g, '/');

    // 智能拼接路径
    const combined = [unifiedBase, unifiedSub]
        .join('/') // 安全拼接
        .replace(/\/+/g, '/') // 合并连续斜杠
        .replace(/^\/+|\/+$/g, ''); // 去除首尾多余斜杠

    // 重新添加尾部斜杠（如果需要）
    return combined + (combined.endsWith('/') ? '' : '');
}

function removePrefix(path) {
    // 处理空路径情况
    if (!path) return ''

    // 分割路径为数组
    const parts = path.split('/')

    if (parts[0] == 'FileList' && parts[1] == versionID) {
        // 移除前两个元素（FileList和uid）
        const remaining = parts.slice(2)

        // 重组路径字符串
        return true, remaining.join('/')
    } else {
        return false, ''
    }
}

function getParentDirectory(path) {
    // 统一替换所有反斜杠为正斜杠（兼容 Windows 路径）
    const normalizedPath = path.replace(/\\/g, '/');

    // 分割路径并过滤空段（处理多余斜杠）
    const segments = normalizedPath.split('/').filter(segment => segment !== '');

    // 移除最后一个路径段（如果存在）
    if (segments.length > 1) {
        segments.pop();
        return segments.join('/'); // 重新拼接路径
    }

    // 根目录或无父目录时返回 null
    return null;
}

// 通用创建按钮函数
function createButton(iconClass, btnClass, clickHandler) {
    const btn = document.createElement('button');
    btn.className = `action-btn ${btnClass}`;

    const icon = document.createElement('i');
    icon.className = iconClass;
    btn.appendChild(icon);

    btn.addEventListener('click', clickHandler);
    return btn;
}

async function renameFile(oldPath, newFileName, strID) {
    try {
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);
        const response = await fetch('/api/file/rename', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify({
                old_path: oldPath,
                new_name: newFileName,
                id: strID,
            })
        });

        // 首先检查HTTP状态
        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error(`HTTP错误 ${response.status}`);
            }

        }

        const result = await response.json();

        // 根据Beego的响应格式处理
        if (result.code === "0") {
            console.log('重命名成功');
            //alert('重命名成功');
            return {
                success: true,
                error: ''
            };
        } else {
            throw new Error(result.message || '未知错误');
        }
    } catch (error) {
        console.error('重命名失败:', error);
        return {
            success: false,
            error: error.message || '请求发送失败'
        };
    }
}

async function deleteSelf(file) {
    // 获取认证信息（根据实际存储方式调整）
    const token = localStorage.getItem('authToken');
    if (!token) AuthReDirection(false);

    const response = await fetch(`/api/file/delete`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `${token}`,
        },
        body: JSON.stringify({ id: file.id, machine: machineID, path: file.path, name: file.name, version: versionID, isDir: file.isDir })
    })

    if (!response.ok) {
        if (response.status == 401) {
            AuthReDirection(false);
        }
        else if (response.status == 402) {
            const data = await response.json();
            AuthPermissionErr(data.error);
            return
        }
        else {
            alert(`删除失败,接口调用失败`)
        }
    } else {
        return response;
    }
}

// 发送 GET 请求的函数封装
async function fetchSubVersions(params = {}) {
    // 构建查询参数
    const queryParams = new URLSearchParams({
        page: params.page || 1,
        pageSize: params.pageSize || 10,
        ...(params.version && { version: params.version })
        // 可根据需要扩展其他查询参数
    }).toString();

    try {
        const response = await fetch(`/api/version/subversion/list?${queryParams}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.code !== 200) {
            throw new Error(result.message || '请求失败');
        }

        return result;

    } catch (error) {
        console.error('请求失败:', error);
        throw error; // 重新抛出错误供外部处理
    }
}


async function GetVersionList(params) {
    try {
        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        const response = await fetch(`/api/version/list?${new URLSearchParams(params)}`, {
            method: 'GET',
            headers: new Headers({
                'Authorization': `${token}`
            }),
        });
        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error('数据加载失败')
            }
        }

        return response.json();
    } finally {

    }
}


function initActionButtons(config) {
    const container = document.querySelector('.fixed-action-bar');
    container.innerHTML = ''; // 清空原有按钮

    config.forEach(btn => {
        const button = document.createElement('button');
        button.className = `btn ${btn.type}`;
        button.setAttribute('onclick', btn.action);
        button.innerHTML = btn.text;
        container.appendChild(button);
    });
}


function updateColumnLabel(columnClass, newLabel, tableElement) {
    const thElement = tableElement.querySelector(`thead .${columnClass}`);
    if (thElement) {
        thElement.textContent = newLabel;
        thElement.setAttribute('data-dynamic-label', newLabel); // 可选：存储状态标记
    }
}

function createVersion() {
    const createVersionPage = document.getElementById('create-version-page');
    const versionForm = document.getElementById('version-form');

    createVersionPage.style.display = 'flex';
    versionForm.reset(); // 清空表单历史数据
}

// 关闭弹窗的通用方法
function CloseCreateVersionPage() {
    const createModal = document.getElementById('create-version-page');

    createModal.style.display = 'none';
}

async function CreateVersionBtnFunc() {
    try {
        const inputName = document.getElementById('input-name-version');

        const remark = document.getElementById('input-remark-version');

        if (inputName == null) {
            alert("获取版本编辑框失败")
            return
        }

        if (remark == null) {
            alert("获取说明编辑框失败")
            return
        }



        // 收集表单数据
        const machineData = {
            name: inputName.value,
            version: "",
            created: "",
            creator: "",
            remark: remark.value,
            machine_id: machineID,
        };

        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        // 发送POST请求
        const response = await fetch('/api/version/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify(machineData)
        })

        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error('创建版本失败,未知错误')
            }
        }

        const result = await response.json();

        if (result.code !== '0') {
            throw new Error(result.message);
        }

        //alert("创建成功")
        ShowNotice({
            message: '创建成功',
            type: 'success',
            duration: 2000
        });

        CloseCreateVersionPage();
        renderVersionPath();

    } catch (error) {
        alert(error)
    }
}

function deleteVersion() {
    alert("功能待开发");
}



// 获取所有列组容器
const getColumnGroups = () => {
    return Array.from(document.getElementsByClassName('version_file_group'));
};

class ColumnGroupManager {
    constructor() {
        this.groups = getColumnGroups();
    }

    add(className, position = -1) {
        this.groups.forEach(group => {
            const col = document.createElement('col');
            col.className = className;
            position === -1
                ? group.appendChild(col)
                : group.insertBefore(col, group.children[position]);
        });
        return this;
    }

    remove(className) {
        this.groups.forEach(group => {
            Array.from(group.children)
                .filter(col => col.classList.contains(className))
                .forEach(col => col.remove());
        });
        return this;
    }

    update(oldClass, newClass) {
        this.groups.forEach(group => {
            Array.from(group.children)
                .filter(col => col.classList.contains(oldClass))
                .forEach(col => {
                    col.classList.replace(oldClass, newClass);
                });
        });
        return this;
    }
}

function formatFileSize(size) {
    const unit = 1024;
    if (size < unit) {
        return `${size} B`;
    }

    let div = unit;
    let exp = 0;
    // 与 Go 版本保持一致的进制计算逻辑
    for (let n = Math.floor(size / unit); n >= unit; n = Math.floor(n / unit)) {
        div *= unit;
        exp++;
    }

    // 精确控制小数点格式
    const formatted = (size / div).toFixed(1);
    // 去除 .0 后缀（可选）
    const cleanFormat = formatted.endsWith('.0')
        ? formatted.slice(0, -2)
        : formatted;

    return `${cleanFormat} ${'KMGTPE'[exp]}B`;
}


function renderFileIcon(filename, isDir) {
    if (isDir) {
        return "📁 ";
    }

    const parts = filename.split('.');
    if (parts.length == 2) {
        let fileType = parts.pop().toLowerCase()
        switch (fileType) {
            case 'exe':
                return '🖥️ ';
            case 'ini':
                return " ⚙️";
            case 'cfg':
                return " ⚙️";
            default:
                return '📄 ';
        }

    } else {
        return "📄 "
    }
}